package com.framework.boc.admin.security.sms;

import com.framework.boc.admin.security.service.MyUserDetailsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Component
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken)authentication;
        UserDetails userDetails = null;
        try {
            userDetails = myUserDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());
        } catch (UsernameNotFoundException e) {
            throw e;
        }
        if (Objects.isNull(userDetails)) {
            throw new InternalAuthenticationServiceException("无法获取权限信息");
        }
        if (!StringUtils.equals((String) authenticationToken.getCredentials(), userDetails.getPassword())) {
            throw new BadCredentialsException("短信验证码错误");
        }
        SmsCodeAuthenticationToken token = new SmsCodeAuthenticationToken(userDetails.getUsername(), userDetails.getAuthorities());
//        token.setDetails(userDetails);

        // 移除session中存储的验证码
        httpServletRequest.getSession().removeAttribute((String) authenticationToken.getPrincipal());

        return token;
    }

    @Override
    public boolean supports(Class<?> authenticationClass) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authenticationClass);
    }
}
